package com.sowka.miko.weather;

import java.util.Hashtable;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.osgi.service.prefs.Preferences;
import org.osgi.util.tracker.ServiceTracker;

import com.sowka.miko.util.Prefs;
import com.sowka.miko.weather.provider.WeatherProvider;

public class Activator implements BundleActivator, ServiceListener {

	// TODO think of better mechanism to specify default provider
	
	private static Activator instance;
	
	public static Activator getInstance() {
		return instance;
	}
	
	private BundleContext context;

	private WeatherService service;
	private ServiceTracker weatherServiceTracker;
	
	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext context) throws Exception {
		instance = this;
		this.context = context;
		
		Preferences prefs = Prefs.getPreferences();
		
		String provider = prefs.get(Prefs.DEFAULT_PROVIDER, Prefs.DEFAULT_PROVIDER_DEFAULT);
		
		service = new WeatherServiceImpl(provider);

		// register the service
		Hashtable<String, Object> props = new Hashtable<String, Object>();
		props.put(WeatherService.DEFAULT_PROVIDER_PROP, provider);
		context.registerService(WeatherService.class.getName(), service, props);

		// create a tracker and track the service
		weatherServiceTracker = new ServiceTracker(context, WeatherService.class.getName(), null);
		weatherServiceTracker.open();

		// have a service listener to implement the whiteboard pattern
	    context.addServiceListener(this, "(objectclass=" + WeatherProvider.class.getName() + ")");
		
		// grab the service
		service = (WeatherService) weatherServiceTracker.getService();
	}

	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
		// close the service tracker
		weatherServiceTracker.close();
		weatherServiceTracker = null;

		service = null;
		context = null;
	}

	public void serviceChanged(ServiceEvent event) {
		ServiceReference serviceRef = event.getServiceReference();
		switch(event.getType()) {
			case ServiceEvent.REGISTERED:
			{
				WeatherProvider provider = (WeatherProvider) context.getService(serviceRef);
				service.registerProvider((String) serviceRef.getProperty(WeatherProvider.PROVIDER_ID), provider);
			}
			break;
			case ServiceEvent.UNREGISTERING:
			{
				service.unregisterProvider((String) serviceRef.getProperty(WeatherProvider.PROVIDER_ID));
			}
			break;
		}
	}

}
